package com.streetsmart;

/**
 * 
 * @author bhavani sudha
 *
 */
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.view.ViewGroup;
import android.widget.CursorAdapter;

/**
 * Used for populating the autocomplete address data
 * 
 */

public class MySuggestionsAdapter extends CursorAdapter {

	Context context;
	private static DBManager db = null;
	
	public MySuggestionsAdapter(Context context, Cursor cur) {
		super(context, cur);
		this.context = context;
	}

	@Override
	public void bindView(View view, Context context, Cursor cur) {
		int columnIndex = cur.getColumnIndex("address");
		((TextView) view).setText(cur.getString(columnIndex));
	}

	@Override
	public String convertToString(Cursor cur) {
		int columnIndex = cur.getColumnIndex("address");
		return cur.getString(columnIndex);
	}

	@Override
	public View newView(Context context, Cursor cur, ViewGroup parent) {
		final LayoutInflater inflater = LayoutInflater.from(context);
		final TextView view = (TextView) inflater.inflate(
				android.R.layout.simple_dropdown_item_1line, parent, false);
		int columnIndex = cur.getColumnIndex("address");
		view.setText(cur.getString(columnIndex));
		return view;
	}

	/*@Override
	public void changeCursor(Cursor cursor) {
		cursor.close();
		db.close();
	}*/

	@Override
	public Cursor runQueryOnBackgroundThread(CharSequence constraint) {

		db = new DBManager(context);
		Cursor currentCursor = null;

		if (getFilterQueryProvider() != null) {
			return getFilterQueryProvider().runQuery(constraint);
		}

		String args = "";

		if (constraint != null) {
			args = constraint.toString();
		}

		currentCursor = db.getAllUserAddresses(args);

		return currentCursor;
	}

	public void close() {
		if (db != null) {
			db.close();
		}
	}
}
